package com.wutianyi.controller.product;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.wutianyi.module.company.Company;
import com.wutianyi.module.product.dataobject.ProductDTO;
import com.wutianyi.module.services.CompanyServices;
import com.wutianyi.module.services.ProductServices;
import com.wutianyi.utils.MyStringUtils;

@Controller
public class ProductIndexController {
	
	@Autowired
	private ProductServices productServices;
	
	@Autowired
	private CompanyServices companyServices;
	
	@RequestMapping("/{cId}/*")
	public ModelAndView productList(@PathVariable String cId, String type,
			@RequestParam(defaultValue = "1") int pageNo,
			@RequestParam(defaultValue = "10") int pageSize) {
		ModelAndView modelAndView = new ModelAndView("product/product_list");
		
		int companyId = MyStringUtils.convertToInt(cId, 1);
		
		int count = productServices.listProductCountByCompanyId(companyId);
		
		List<ProductDTO> products = productServices.listProductDTOsByCompanyId(companyId, pageNo,
				pageSize);
		
		Company company = companyServices.getCompanyById(companyId);
		
		int totalNo = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
		modelAndView.addObject("totalPage", totalNo);
		modelAndView.addObject("pageNo", pageNo);
		modelAndView.addObject("pageSize", pageSize);
		modelAndView.addObject("products", products);
		modelAndView.addObject("cId", cId);
		modelAndView.addObject("company", company);
		
		return modelAndView;
	}
	
	@RequestMapping("/product_detail.do")
	public ModelAndView productDetail(@RequestParam(value = "id", defaultValue = "0") int id) {
		ModelAndView modelAndView = new ModelAndView("product/product_detail");
		
		ProductDTO product = productServices.getProductDTO(0, id);
		
		Company company = companyServices.getCompanyById(product.getProduct().getCompanyId());
		
		modelAndView.addObject("product", product);
		modelAndView.addObject("company", company);
		
		return modelAndView;
	}
	
	@ModelAttribute("companys")
	public List<Company> listCompanys() {
		return companyServices.listCompanys();
	}
}
